﻿using System;
using System.Net;
using Microsoft.SPOT;
using Microsoft.SPOT.Input;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;

using Microsoft.SPOT.Touch;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.IO;

namespace eHouse
{
    public class Program : Microsoft.SPOT.Application
    {

        private void onAlarm()
        {
            new AlarmWindow();

        }

        private const int port = 6969;

        public static void Main()
        {
            // Create the object that configures the GPIO pins to buttons.
            //GPIOButtonInputProvider inputProvider = new GPIOButtonInputProvider(null);
            Microsoft.SPOT.Hardware.Utility.SetLocalTime(new DateTime(2012, 10, 15, 12, 0, 0));

            Drivers.createInstance();            

            Program myApplication = new Program();

            new Thread(myApplication.startServer).Start();
            new Thread(myApplication.checkAlert).Start();

            Touch.Initialize(myApplication);

            // Start the application
            myApplication.Run(myApplication.CreateWindow());
        }

        static Window mainWindow;

        public Window CreateWindow()
        {
            // Create a window object and set its size to the
            // size of the display.
            mainWindow = new Window();
            mainWindow.Height = SystemMetrics.ScreenHeight;
            mainWindow.Width = SystemMetrics.ScreenWidth;

            Canvas canvas = new Canvas();

            Image image_light = new Image(Resources.GetBitmap(Resources.BitmapResources.light));
            image_light.HorizontalAlignment = HorizontalAlignment.Center;
            Button button_light = new Button(image_light);
            button_light.Width = mainWindow.Width / 2;
            button_light.Height = 2 * mainWindow.Height / 5;
            Canvas.SetTop(button_light, 0);
            Canvas.SetLeft(button_light, 0);
            canvas.Children.Add(button_light);

            Image image_thermo = new Image(Resources.GetBitmap(Resources.BitmapResources.thermometer));
            image_thermo.HorizontalAlignment = HorizontalAlignment.Center;
            Button button_thermo = new Button(image_thermo);
            button_thermo.Height = 2 * mainWindow.Height / 5;
            button_thermo.Width = mainWindow.Width / 2;
            Canvas.SetTop(button_thermo, 0);
            Canvas.SetLeft(button_thermo, mainWindow.Width / 2);
            canvas.Children.Add(button_thermo);

            Image image_window = new Image(Resources.GetBitmap(Resources.BitmapResources.window));
            image_window.HorizontalAlignment = HorizontalAlignment.Center;
            Button window_button = new Button(image_window);
            window_button.Width = mainWindow.Width / 2;
            window_button.Height = 2 * mainWindow.Height / 5;
            Canvas.SetTop(window_button, 2 * mainWindow.Height / 5);
            Canvas.SetLeft(window_button, 0);
            canvas.Children.Add(window_button);

            Image image_irrigation = new Image(Resources.GetBitmap(Resources.BitmapResources.watering));
            image_irrigation.HorizontalAlignment = HorizontalAlignment.Center;
            Button irrigation_button = new Button(image_irrigation);
            irrigation_button.Width = mainWindow.Width / 2;
            irrigation_button.Height = 2 * mainWindow.Height / 5;
            Canvas.SetTop(irrigation_button, 2 * mainWindow.Height / 5);
            Canvas.SetLeft(irrigation_button, mainWindow.Width / 2);
            canvas.Children.Add(irrigation_button);

            Image image_info = new Image(Resources.GetBitmap(Resources.BitmapResources.info));
            image_info.HorizontalAlignment = HorizontalAlignment.Center;
            image_info.VerticalAlignment = VerticalAlignment.Center;
            Button button_info = new Button(image_info);
            button_info.Width = mainWindow.Width / 2;
            button_info.Height = mainWindow.Height / 5;
            Canvas.SetBottom(button_info, 0);
            Canvas.SetLeft(button_info, 0);
            canvas.Children.Add(button_info);

            Image image_settings = new Image(Resources.GetBitmap(Resources.BitmapResources.settings));
            image_settings.HorizontalAlignment = HorizontalAlignment.Center;
            image_settings.VerticalAlignment = VerticalAlignment.Center;
            Button button_settings = new Button(image_settings);
            button_settings.Width = mainWindow.Width / 2;
            button_settings.Height = mainWindow.Height / 5;
            Canvas.SetBottom(button_settings, 0);
            Canvas.SetRight(button_settings, 0);
            canvas.Children.Add(button_settings);


            button_light.Click += new EventHandler(lightButton_Click);
            button_thermo.Click += new EventHandler(thermoButton_Click);
            window_button.Click += new EventHandler(windowButton_Click);
            irrigation_button.Click += new EventHandler(irrigationButton_Click);
            button_info.Click += new EventHandler(infoButton_Click);
            button_settings.Click += new EventHandler(settingsButton_Click);


            mainWindow.Child = canvas;


            // Connect the button handler to all of the buttons.
            mainWindow.AddHandler(Buttons.ButtonUpEvent, new RoutedEventHandler(OnButtonUp), false);

            // Set the window visibility to visible.
            mainWindow.Visibility = Visibility.Visible;

            // Attach the button focus to the window.
            Buttons.Focus(mainWindow);

            return mainWindow;
        }

        void lightButton_Click(object sender, EventArgs evt)
        {
            Debug.Print("light button pressed");
            LightsWindow lw = new LightsWindow(mainWindow);
        }

        void thermoButton_Click(object sender, EventArgs evt)
        {
            Debug.Print("Temperature button pressed");
            TemperatureWindow tw = new TemperatureWindow(mainWindow);
        }

        void windowButton_Click(object sender, EventArgs evt)
        {
            Debug.Print("Window button pressed");
            WindowWindow ww = new WindowWindow(mainWindow);
        }

        void irrigationButton_Click(object sender, EventArgs evt)
        {
            Debug.Print("irrigation button pressed");
            IrrigationWindow iw = new IrrigationWindow(mainWindow);
        }

        void infoButton_Click(object sender, EventArgs evt)
        {
            Debug.Print("info button pressed");
            InfoWindow iw = new InfoWindow(mainWindow);
        }

        void settingsButton_Click(object sender, EventArgs evt)
        {
            Debug.Print("settings button pressed");
            SettingsWindow sw = new SettingsWindow(mainWindow);
        }

        private void OnButtonUp(object sender, RoutedEventArgs evt)
        {
            ButtonEventArgs e = (ButtonEventArgs)evt;

            // Print the button code to the Visual Studio output window.
            Debug.Print(e.Button.ToString());
        }

        private void startServer()
        {
            const Int32 c_port = 6500;

            // Create a socket, bind it to the server's port, and listen for client 
            // connections.
            Socket server = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, c_port);
            server.Bind(localEndPoint);
            server.Listen(Int32.MaxValue);
            while (true)
            {
                // Wait for a client to connect.
                Socket clientSocket = server.Accept();
                Debug.Print("Client Connected");
                ComManager cm = new ComManager(clientSocket);
                new Thread(cm.run).Start();
            }
        }

        private void checkAlert()
        {
            while (true)
            {                      

                if (!Drivers.getInstance().AlarmTrigger.Read())
                {
                    Alarm.getInstance().AlarmOn();
                    this.Dispatcher.BeginInvoke(new DispatcherOperationCallback((object o) => { onAlarm(); return o; }), null);
                                       
					Thread.Sleep(10000);
					if (Alarm.alarmOn) {
						ConnectionManager.GetInstance().SendNotification("Alert: Intruders");              
					}
                }
                Thread.Sleep(5000);
            }
        }      

    }
}
